package cn.com.jinhao.provider.business.controller;

import cn.com.jinhao.hotline.commons.base.constant.SystemConstant;
import cn.com.jinhao.hotline.commons.util.Algorithm;
import cn.com.jinhao.hotline.commons.util.ExeclUtil;
import cn.com.jinhao.hotline.commons.util.MessageDigestUtils;
import cn.com.jinhao.hotline.commons.util.RestResponse;
import cn.com.jinhao.hotline.commons.vo.system.SysDictResponseVO;
import cn.com.jinhao.provider.business.service.SysDictService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping(value = "/file")
@Api(tags = {"附件"})
public class FileUploadController  {

    SysDictService sysDictService;
    @Autowired
    private FileUploadController(SysDictService sysDictService){
        this.sysDictService = sysDictService;
    }

    @ApiOperation(value = "上传附件")
    @PostMapping(value = "/fileupload")
    public RestResponse<java.lang.String> FileUpLoad(HttpServletRequest request, HttpServletResponse response) throws  JSONException {
        JSONObject fileJsonS = new JSONObject();
        //上传附件 <input type="file" name="fileName">
        List<MultipartFile> files = ((MultipartHttpServletRequest)request).getFiles("fileName");
        if(files.isEmpty()){
            fileJsonS.put("error","检查无附件上传");
            return new RestResponse<>(fileJsonS.toString());
        }
        //上传地址
        String path = null;
        //上传大小
        int size = 0;
        //上传格式
        String type = null;
        Map<String, Object> fileMap = sysDictService.querySysDict("SYS_FILE","",0,0);
        for(Map.Entry<String, Object> entry : fileMap.entrySet()){
            if (entry.getKey().equals("list")){
                List<SysDictResponseVO> SysDictResponseVOList = (List<SysDictResponseVO>) entry.getValue();
                for (SysDictResponseVO SysDictResponseVO:SysDictResponseVOList) {
                    if(SystemConstant.FileType.PATH.getCode().equals(SysDictResponseVO.getCode())){
                        path = SysDictResponseVO.getSysValue();
                    }else if(SystemConstant.FileType.SIZE.getCode().equals(SysDictResponseVO.getCode())){
                        size = Integer.valueOf(SysDictResponseVO.getSysValue());
                    }else if(SystemConstant.FileType.TYPE.getCode().equals(SysDictResponseVO.getCode())){
                        type = SysDictResponseVO.getSysValue();
                    }
                }
            }
        }

        for (MultipartFile file:files) {
            //上传文件名称
            String fileName = file.getOriginalFilename();
            //附件格式
            String suffixName = fileName.substring(fileName.lastIndexOf(".")+1);
            if(!type.contains(suffixName)){
                fileJsonS.put("error","上传附件格式不符合要求");
                return new RestResponse<>(fileJsonS.toString());
            }
            int fileSize = (int) Math.ceil(file.getSize()/1024);
            if(fileSize > size){
                fileJsonS.put("error","上传附件过大不符合要求");
                return new RestResponse<>(fileJsonS.toString());
            }
        }
        JSONArray fileJsonArray = new JSONArray();
        for (MultipartFile file:files) {
            JSONObject filejson = new JSONObject();
            //上传文件名称
            String fileName = file.getOriginalFilename();
            //原文件名
            filejson.put("atch",fileName);
            //附件格式
            String suffixName = fileName.substring(fileName.lastIndexOf(".")+1);
            //格式
            filejson.put("fsuf",suffixName);
            int fileSize = (int) Math.ceil(file.getSize()/1024);
            //大小
            filejson.put("fsiz",fileSize);
            if(file.isEmpty()){
                fileJsonS.put("error","检查无附件上传");
                return new RestResponse<>(fileJsonS.toString());
            }else{
                String fmd5= MessageDigestUtils.encrypt(fileName.substring(fileName.lastIndexOf(".")-1),Algorithm.MD5);
                filejson.put("fmd5",fmd5);
                filejson.put("nfnm",fileName+"_"+fmd5+suffixName);
                File dest = new File(path+"/"+fileName+"_"+fmd5+"."+suffixName);
                //判断附件父目录是否存在
                if(!dest.getParentFile().exists()){
                    dest.getParentFile().mkdir();
                }
                try {
                    file.transferTo(dest);
                } catch (Exception e){
                    e.printStackTrace();
                    fileJsonS = null;
                    fileJsonS.put("error","附件上传失败");
                    return new RestResponse<>(fileJsonS.toString());
                }
            }
            fileJsonArray.add(filejson);
        }
        fileJsonS.put("fileArray",fileJsonArray);
        fileJsonArray  =  null;
        return new RestResponse<>(fileJsonS.toJSONString());
    }




    @ApiOperation(value = "导出execl")
    @GetMapping(value = "/execl")
    public RestResponse<java.lang.String> exportExecl(){
        List<String> list = new ArrayList<>();
        list.add("1");
        list.add("2");
        list.add("3");
        list.add("4");
        list.add("5");
        JSONArray JSONArray = new JSONArray();
        for(int i=0 ;i<5 ;i++){
            JSONObject json = new JSONObject();
            for (String str: list) {
                json.put(str,str);
            }
            JSONArray.add(json);
        }
        String  a= new ExeclUtil().exportExecl(list,JSONArray,"F:\\");
        return new RestResponse<>(a);
    }
}
